package controllers

import (
	"acs/management/models"
	"errors"
	"net/http"
	"strconv"
	"sync"
	"time"

	"github.com/labstack/echo"
)

//历史访问数据的保存个数
const histroyCap int = 60 * 24

func init() {
	histroyAccessNumber = make(map[string]int32, histroyCap)
	for i := 0; i < histroyCap; i++ {
		histroyAccessNumber[strconv.Itoa(i)] = 0
	}
}

var histroyAccessNumber map[string]int32
var historyAccessMet sync.RWMutex

func setAccessSpeed() {
	now := time.Now()
	thisMinute := strconv.Itoa(now.Minute() + now.Hour()*60)
	historyAccessMet.Lock()
	histroyAccessNumber[thisMinute] = histroyAccessNumber[thisMinute] + 1
	historyAccessMet.Unlock()
}

//OutApiListAPPHandler
func OutApiListAPPHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	models.CheckError(checkOutAPI(c))
	currentPageStr := c.Param("page")
	currentPage, switchErr := strconv.Atoi(currentPageStr)
	models.CheckError(switchErr)

	currentStepStr := c.Param("step")
	currentStep, switchErr2 := strconv.Atoi(currentStepStr)
	models.CheckError(switchErr2)
	if currentPage < 1 || currentStep < 1 {
		panic(errors.New("参数不符合标准。"))
	}
	allStr := c.Param("all")
	query := make(map[string]interface{})

	if allStr == "0" {
		// 不全拿，只拿可用的
		query["enable"] = 1
	}
	datalist, _, listErr := models.GetAllTApp(query, nil, nil, nil, int64((currentPage-1)*currentStep), int64(currentStep), false)
	models.CheckError(listErr)

	c.JSON(http.StatusOK, models.ExportJson(models.Right_Status, nil, datalist, -1))
	return
}

//OutApiListPatchByAPPHandler
func OutApiListPatchByAPPHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	models.CheckError(checkOutAPI(c))
	//设置是否需要检测登录。 用在下面的ListPatchByAppHandler 函数内判读。
	c.Set("needCheckLogin", false)
	ListPatchByAppHandler(c)
	return
}

//checkOutApi 检查用户的token是否有权限访问此api
func checkOutAPI(c echo.Context) error {
	setAccessSpeed()
	token := c.QueryParam("token")
	if models.CheckApiUrlEnable(c.Path()) == false {
		return errors.New("该接口不可使用")
	}
	if models.CheckApiUser(token) == false {
		return errors.New("该账户不可使用")
	}
	if models.GetAPIURLListByToken(token, c.Path()) == false {
		return errors.New("该账户无权访问此接口")
	}
	return nil
}

//GetAccessAPISpeedHandler 获取api 被调用的频率数据
func GetAccessAPISpeedHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	models.CheckLogin(c)
	allStr := c.Param("all")
	if allStr == "1" {
		c.JSON(http.StatusOK, histroyAccessNumber)
	} else {
		now := time.Now()
		thisMinute := strconv.Itoa(now.Minute() + now.Hour()*60)
		itemMap := make(map[string]int32)
		itemMap[thisMinute] = histroyAccessNumber[thisMinute]
		c.JSON(http.StatusOK, itemMap)
	}
	return
}
